//
//  WBRefreshControl.swift
//  LVWeibo
//
//  Created by lv on 15/7/3.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit
import FFAutoLayout

class WBRefreshControl: UIRefreshControl {

    override init() {
        super.init()
        
        // 添加刷新视图
        addSubview(refreshView)
        refreshView.ff_AlignVertical(ff_AlignType.CenterCenter, referView: self, size: CGSizeMake(156, 60))
        
        /// KVO监听Frame的变化,自己监听自己
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
    }
    
    /// 注销监听(必须)
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    
    // 提示图标标记
    private var showTipFlag = false
    // 加载图标标记
    private var showLoadingFlag = false
    
    /// 监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if frame.origin.y > 0 {
            return
        }
        // 正在加载数据，显示加载动画
        if refreshing && !showLoadingFlag {
            refreshView.startLoadingAnim()
            showLoadingFlag = true
            return
        }
        
        if frame.origin.y < -50 && !showTipFlag {
            print("翻过来")
            showTipFlag = true
            refreshView.rotateTipImage(showTipFlag)
        }else if frame.origin.y >= -50 && showTipFlag {
            print("转过去")
            showTipFlag = false
            refreshView.rotateTipImage(showTipFlag)
        }

    }
    
    //MARK: - 结束刷新
    override func endRefreshing() {
        super.endRefreshing()
        
        // 结束动画
        refreshView.stopLoadingAnim()
        
        // 重设标识
        showLoadingFlag = false
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // 懒加载刷新视图
    lazy var refreshView: WBRefreshView = WBRefreshView.refreshView()
}

//Mark:- 刷新视图
class WBRefreshView: UIView {
    
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipImage: UIImageView!
    @IBOutlet weak var loadImage: UIImageView!
    
    class func refreshView() -> WBRefreshView {
        return NSBundle.mainBundle().loadNibNamed("WBRefreshView", owner: nil, options: nil).last as! WBRefreshView
    }
    ///  旋转提示图标
    private func rotateTipImage(clockWise: Bool) {
        
        // 旋转角度
        var angle = M_PI
        
        angle += clockWise ? -0.01 : 0.01
        // 动画实现
        UIView.animateWithDuration(0.25) { () -> Void in
            self.tipImage.transform = CGAffineTransformRotate(self.tipImage.transform, CGFloat(angle))
        }
    }
    
    ///  加载数据动画
    private func startLoadingAnim() {
        tipView.hidden = true
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        loadImage.layer.addAnimation(anim, forKey: nil)
    }
    
    ///  停止数据加载动画
    private func stopLoadingAnim() {
        tipView.hidden = false
        loadImage.layer.removeAllAnimations()
    }
}
